package com.cdh.sms.controller;

import com.aliyuncs.exceptions.ClientException;
import com.cdh.base.DIYException;
import com.cdh.sms.service.SmsService;
import com.cdh.utils.result.Restful;
import com.cdh.utils.result.ResultCodeEnum;
import com.cdh.utils.util.FormUtil;
import com.cdh.utils.util.RandomUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author by cdh
 * @description:
 * @Date: Created in 10:45 on 2021/3/3
 */
@Api(value = "短信服务")
@RestController
@RequestMapping("/api/sms")
@CrossOrigin
@Slf4j
public class ApiSmsController {

    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取验证码
     * @param phone
     * @return
     */
    @GetMapping("send/{phone}")
    public Restful getCode(@PathVariable String phone) throws ClientException {
        // 校验手机号是否合法
        if(StringUtils.isEmpty(phone) || !FormUtil.isMobile(phone)){
            log.error("手机号不正确");
            throw new DIYException(ResultCodeEnum.LOGIN_PHONE_ERROR.getCode(),
                    ResultCodeEnum.LOGIN_PHONE_ERROR.getMessage());
        }

        // 生成验证码
        String verificationCode = RandomUtil.getSixBitRandom();

        // 发送验证码
        // smsService.send(phone,verificationCode);

        // 存储验证码到redis 5分钟失效
        redisTemplate.opsForValue().set(phone, verificationCode,5, TimeUnit.MINUTES);

        return Restful.ok().message("短信发送成功");
    }
}
